<template>
  <div class="search-page">
    <div class="page-header">
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item
          v-for="(slide, idx) in carouselImages"
          :key="`carousel-${idx}`"
        >
          <div class="carousel-slide">
            <img
              :src="slide.image"
              class="slide-image"
              :alt="`轮播图${idx + 1}`"
            />
          </div>
        </van-swipe-item>
      </van-swipe>
    </div>

    <div class="search-container">
      <div class="search-input-section">
        <input
          type="text"
          v-model="page.keyword"
          placeholder="请输入演员姓名或编号"
          class="search-input"
          @keyup.enter="handleSearch"
        />
        <button
          class="search-button"
          :style="currentConfig.button"
          @click="handleSearch"
        >
          <i class="fas fa-search"></i> 搜索
        </button>
      </div>

      <!-- 核心修改：筛选按钮添加动态style绑定 -->
      <!-- <div class="search-filters">
        <button
          class="filter-btn"
          :class="{ active: searchType === 'all' }"
          :style="
            searchType === 'all' ? currentConfig.button : filterDefaultStyle
          "
          @click="searchType = 'all'"
        >
          全部
        </button>
        <button
          class="filter-btn"
          :class="{ active: searchType === 'id' }"
          :style="
            searchType === 'id' ? currentConfig.button : filterDefaultStyle
          "
          @click="searchType = 'id'"
        >
          编号
        </button>
        <button
          class="filter-btn"
          :class="{ active: searchType === 'name' }"
          :style="
            searchType === 'name' ? currentConfig.button : filterDefaultStyle
          "
          @click="searchType = 'name'"
        >
          姓名
        </button>
      </div> -->

      <div class="search-results" v-if="showResults">
        <div class="results-header">
          <p>找到 {{ contestants.length }} 个结果</p>
          <button
            class="reset-btn"
            :style="{ color: currentConfig.commonColor }"
            @click="resetSearch"
          >
            重置
          </button>
        </div>

        <!-- <div class="no-results" v-if="contestants.length === 0">
          <i class="fas fa-search-minus"></i>
          <p>没有找到匹配的演员</p>
          <p>请尝试其他关键词</p>
        </div> -->

        <!-- <div class="contestants-list">
          <div
            class="contestant-item"
            v-for="(item, index) in contestants"
            :key="index"
          >
            <span class="contestant-rank">{{ index + 1 }}</span>
            <img
              :src="item.img"
              alt="演员照片"
              class="contestant-img"
              :title="item.name"
            />
            <div class="contestant-info">
              <p class="contestant-name">{{ item.name || "未命名" }}</p>
              <p class="contestant-id">编号: {{ item.id }}</p>
              <p class="contestant-votes">
                <i class="fas fa-vote-yea"></i> {{ item.votes }} 票
              </p>
            </div>
            <button
              class="vote-button"
              :style="currentConfig.button"
              @click="handleVote(item.id)"
            >
              投票
            </button>
          </div>
        </div> -->
        <!-- 演员列表 -->
        <div class="player-list-section">
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
            :error.sync="error"
            error-text="请求失败，点击重新加载"
            style="padding-bottom: 20px"
          >
            <div
              class="players-container"
              :class="listDisplayMode"
              v-if="contestants.length > 0"
            >
              <div
                class="player-item"
                v-for="(item, i) in contestants"
                :key="`${item.id}-${i}`"
              >
                <div class="player-rank">
                  {{ item.activityNum }}
                </div>
                <div class="player-avatar-container">
                  <van-image
                    round
                    width="70px"
                    height="70px"
                    :src="
                      item.imageUrl && item.imageUrl.trim()
                        ? item.imageUrl
                        : require('@/assets/list_touxiang.png')
                    "
                  />
                  <!-- <div class="online-indicator" v-if="i % 3 === 0"></div> -->
                </div>
                <div class="player-info">
                  <div class="player-name">{{ item.name }}</div>
                  <div class="player-votes">
                    <van-icon name="like" color="#ee0a24" />
                    <span>{{ item.voteCount }}</span> 票
                  </div>
                </div>
                <van-button
                  round
                  size="small"
                  :style="currentConfig.button"
                  @click="voteForPlayer(item)"
                >
                  投票
                </van-button>
              </div>
            </div>
            <!-- <div class="empty-state" v-if="filteredContestants.length === 0 && !emptyState">
              <van-empty description="暂无演员数据" />
            </div> -->
          </van-list>
        </div>
      </div>
    </div>

    <!-- 投票成功提示 -->
    <div class="toast" v-if="showToast">
      {{ toastMessage }}
    </div>
    <!-- 弹窗组件 -->
    <PlayerDetails
      :childrenData="passPlayerData"
      @add-event="handleAddEvent"
      @child-event="handleChildEvent"
    ></PlayerDetails>
    <AddTickets
      :childrenAddData="passAddData"
      @AddTickets-event="AddTicketsEvent"
    ></AddTickets>
  </div>
</template>

<script>
import { playerList, activeInfo, getPlayerDetail } from "../api/index.js";
import TabBar from "../components/TabBar.vue";
import { styleConfig } from "@/utils/voteH5StyleConfigs.js";
import { Toast } from "vant"; // 引入Toast（之前遗漏）
import PlayerDetails from "./PlayerModule/PlayerDetails.vue"; //投票
import AddTickets from "../view/AddTickets.vue";

export default {
  components: { TabBar, PlayerDetails, AddTickets },
  computed: {
    currentConfig() {
      return styleConfig[this.templateId] || styleConfig[1];
    },
    currentSlides() {
      return this.currentConfig.slides || [];
    },
    // 新增：合并 mainCover 和 additionalImages 为轮播图数据
    carouselImages() {
      if (!this.activityInfo) return [];

      // 处理 additionalImages（不变）
      let additionalImgs = [];
      try {
        additionalImgs = JSON.parse(this.activityInfo.additionalImages || "[]");
        additionalImgs = additionalImgs.filter((img) => img?.trim());
      } catch (error) {
        console.error("解析 additionalImages 失败:", error);
        additionalImgs = [];
      }

      // 处理 mainCover（核心修改：统一路径+日志）
      const mainCoverImg = this.activityInfo.mainCover?.trim();
      let mainImg = [];
      console.log("🚀 ~ carouselImages ~ mainCoverImg:", mainCoverImg);
      if (mainCoverImg) {
        try {
          // 提取文件名（假设 mainCoverImg 是 "/assets/banner_ping.webp"）
          const fileName = mainCoverImg.split("/").pop(); // 得到 "banner_ping.webp"
          // 固定目录 @/assets，仅动态传入文件名
          const imgPath = require(`@/assets/${fileName}`);
          mainImg = [imgPath];
          console.log("mainCover 加载成功");
        } catch (error) {
          console.error("mainCover 加载失败，改用默认图:", error);
          mainImg = [require("@/assets/banner_green.webp")];
        }
      }

      // 合并图片（mainCover+additionalImages）
      const allImgs = [...mainImg, ...additionalImgs].filter((img) => img);
      console.log("🚀 ~ carouselImages ~ allImgs:", allImgs);

      // 最终容错：无图时用默认图
      if (allImgs.length === 0) {
        return [
          { image: require("@/assets/banner_ping.webp") }, // 统一用 @ 绝对路径
        ];
      }

      return allImgs.map((img) => ({ image: img }));
    },
    // 筛选按钮默认样式（未选中时）
    filterDefaultStyle() {
      return {
        backgroundColor: "#fff", // 未选中背景白色
        color: "#333", // 未选中文字色
        border: "1px solid #ddd", // 未选中边框
        borderRadius: "4px", // 统一圆角（与选中态一致）
      };
    },
  },
  watch: {
    currentConfig(newVal) {
      this.$emit("update-config", newVal);
    },
    templateId(newVal, oldVal) {
      console.log(`模板ID从${oldVal}变为${newVal}，样式已更新`);
    },
  },
  data() {
    return {
      activityId: "",
      templateId: 1,
      searchQuery: "",
      searchType: "all", // all, id, name
      showResults: false,
      showToast: false,
      toastMessage: "",
      contestants: [], //列表
      listDisplayMode: "card-mode", //默认  grid list card
      page: {
        keyword: "",
        page: 1,
        pageSize: 10,
      },
      total: 0, // 总数据条数（从接口获取）
      loading: false,

      finished: false,
      error: false, //提示错误信息
      emptyState: false, //初始空状态

      activityInfo: null,

      passPerData: {
        show: false,
        buttonStyle: "",
        activeInfo: {},
      },
      passPlayerData: {
        passCurrentConfig: {},
        show: false,
        playerItem: {},
      },
      passAddData: {
        passCurrentConfig: {},
        show: false,
        playerItem: {},
      },
    };
  },
  mounted() {
    // 从localStorage获取活动ID和模板ID
    this.activityId = localStorage.getItem("vote_activityId") || "";
    this.templateId = Number(localStorage.getItem("vote_templateId")) || 1;

    if (!this.activityId) {
      Toast.fail("未获取到活动ID");
    }
    if (this.activityId) {
      this.fetchInitialData();
    } else {
      // 容错：提取失败时用默认ID，避免页面卡死
      this.activityId = "479c4a01a85440c693ac19ee55f6c68a";
      this.fetchInitialData();
    }
    console.log("搜索页模板样式:", this.currentConfig);
  },
  methods: {
    // 投票：检查本地openId和userInfo后打开详情页
    async voteForPlayer(item) {
      try {
        // 1. 从本地存储读取关键信息（避免依赖this.currentUser，直接读本地更可靠）
        const localOpenId = localStorage.getItem("openId") || "";
        const localNickname = localStorage.getItem("nickname") || "";
        const localAvatar = localStorage.getItem("avatar") || "";

        // 2. 检查条件1：是否已登录（openId存在且非空）
        if (!localOpenId.trim()) {
          Toast.fail("请先登录后再投票");
          // 引导用户登录
          this.authorizeLogin();
          return;
        }

        // 3. 检查条件2：是否已获取完整userInfo（nickname和avatar非空）
        if (!localNickname.trim() || !localAvatar.trim()) {
          Toast.fail("请授权获取用户信息后再投票");
          // 引导用户授权获取用户信息
          await this.redirectToUserInfoAuth();
          // 授权后重新检查，满足则打开详情页
          const updatedNickname = localStorage.getItem("nickname") || "";
          if (updatedNickname.trim()) {
            this.openVoteDetails(item);
          }
          return;
        }
        // 5. 所有条件满足，打开投票详情页
        await this.fetchPlayerDetailAndOpen(item);
        this.openVoteDetails(item);
      } catch (error) {
        console.error("投票前校验失败:", error);
        Toast.fail("操作失败，请稍后重试");
      }
    },
    async fetchPlayerDetailAndOpen(item) {
      try {
        // 2. 核心：调用 getPlayerDetail 接口（仅传选手ID，不处理返回数据）
        await getPlayerDetail(item.id);
        console.log("getPlayerDetail 接口调用成功（选手ID：", item.id, "）");
      } catch (error) {
        // 3. 接口调用失败：仅打印日志+提示，不阻断打开详情页
        console.error("getPlayerDetail 接口调用失败:", error);
        Toast.fail({
          message: "详情接口请求失败",
          duration: 3000,
        });
      } finally {
        // 4. 无论接口成功/失败，都关闭加载提示并打开详情页
        Toast.clear();
      }
    },
    // 新增：复用打开投票详情页的逻辑（避免重复代码）
    openVoteDetails(item) {
      this.passPlayerData = {
        passCurrentConfig: this.currentConfig,
        show: true,
        playerItem: item, // 传递选手信息到详情页
      };
    },

    //返回首页正常关闭所有弹窗 接受值  关闭弹框
    handleChildEvent(data) {
      console.log("data:", data);
      this.passPerData.show = data.isShow;
      this.passPlayerData.show = data.isShow;
    },
    // 回返详情页
    AddTicketsEvent(data) {
      console.log("data:", data);
      this.passAddData.show = data.isShow;
      this.passPlayerData.show = true;
      console.log("🚀 ~ AddTicketsEvent ~ !data.isShow:", !data.isShow);
    },
    handleAddEvent(data, palyerItem) {
      this.passPlayerData.show = data.isShow;
      // this.passAddData.show = true;
      this.passAddData = {
        show: true,
        passCurrentConfig: this.currentConfig,
        playerItem: palyerItem, // 传递选手信息到详情页
      };
      console.log(
        "🚀 ~ handleAddEvent ~ his.passAddData.show:",
        this.passAddData.show
      );
    },
    // handleSearch() {
    //   if (!this.searchQuery.trim()) {
    //     this.showToast = true;
    //     this.toastMessage = "请输入搜索关键词";
    //     this.hideToast();
    //     return;
    //   }
    //   this.showResults = true;
    // },
    // 搜索方法（搜索栏点击搜索/输入回车时触发）
    handleSearch() {
      if (!this.page.keyword.trim()) {
        this.showToast = true;
        this.toastMessage = "请输入搜索关键词";
        this.hideToast();
        return;
      }
      console.log("搜索关键词：", this.page.keyword);
      // 1. 重置分页状态（回到第一页，重新加载）
      this.page.page = 1;
      this.finished = false; // 重置为“未加载完成”
      this.contestants = []; // 清空原有列表数据

      // 2. 手动触发列表加载（调用 onLoad 方法）
      this.onLoad();
    },
    onLoad() {
      this.loading = true; //加载数据
      this.getPlayerList(); // 请求后端数据铺设界面
    },
    // 演员列表
    async getPlayerList() {
      let { page } = this;
      await playerList(this.activityId, this.page)
        .then((res) => {
          console.log("res:", res);
          if (res.data.code == 0) {
            console.log("res选手列表:", res);
            this.showResults = true;
            this.loading = false; // 加载关闭
            // 遍历 list 数组，修改 tbImageslList 中的 tbImage 键名为 url
            const listNew = res.data.data.records || [];
            this.contestants = this.contestants.concat(listNew);
            console.log("this.list :", this.contestants);

            this.$toast.clear(); //清除加载提示
            ++this.page.page;
            if (!res.data.data.records.length) {
              this.finished = true;
              return;
            }
          } else {
            this.finished = true;
            this.loading = false; // 加载关闭
          }
        })
        .catch((error) => {
          console.log("🚀 ~ getPlayerList ~ error:", error);
          //抛出错误
          this.error = true; //显示点击加载更多
          this.emptyState = true; // 区分初始渲染没数据
          this.refreshing = false;
          this.loading = false;
        });
    },
    // 获取活动信息
    async fetchInitialData() {
      try {
        // 显示统一加载提示
        this.$toast.loading({
          message: "加载中...",
          forbidClick: true,
          duration: 0,
        });

        if (!this.activityId) {
          this.$toast.fail("未找到活动ID");
          this.isLoading = false;
          return;
        }

        // 只请求活动详情接口，移除演员列表接口的并行请求
        const activityResponse = await activeInfo(this.activityId);

        // 处理活动详情响应
        console.log(
          "🚀 ~ fetchInitialData ~ activityResponse:",
          activityResponse
        );
        if (activityResponse.data && activityResponse.data.code === 0) {
          console.log(
            "🚀 ~ fetchInitialData ~ this.activityInfo:",
            this.activityInfo
          );
          this.activityInfo = activityResponse.data.data;
          this.listDisplayMode = this.activityInfo.listDisplayMode;
        } else {
          this.$toast.fail(activityResponse.data?.msg || "获取活动信息失败");
        }
        this.isLoading = false;
      } catch (error) {
        console.error("初始数据加载失败:", error);
        this.$toast.fail("网络异常，数据加载失败");
        this.isLoading = false;
      } finally {
        this.isLoading = false; // 结束加载
        // 关闭加载提示
        this.$toast.clear();
      }
    },
    resetSearch() {
      this.page.keyword = "";
      this.showResults = false;
    },
    handleVote(contestantId) {
      const contestant = this.contestants.find((c) => c.id === contestantId);
      if (contestant) {
        contestant.votes++;
        this.showToast = true;
        this.toastMessage = "投票成功！";
        this.hideToast();
      }
    },
    hideToast() {
      setTimeout(() => {
        this.showToast = false;
      }, 2000);
    },
  },
};
</script>

<style scoped lang="scss">
.search-page {
  padding-bottom: 60px; /* 为底部TabBar留出空间 */
  min-height: 100vh;
  background-color: #f5f5f5;
}
.search-container {
  padding: 15px;
}

.search-input-section {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.search-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.search-button {
  border: none;
  border-radius: 20px;
  padding: 0 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: opacity 0.3s; /* 替换原背景色过渡，用透明度过渡更通用 */
}

.search-button:hover {
  opacity: 0.9; /* 通用hover效果，适配任何背景色 */
}

/* 筛选按钮容器 */
.search-filters {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

/* 筛选按钮基础样式（未选中时） */
.filter-btn {
  flex: 1;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  border: none; /* 边框通过动态样式控制，避免冲突 */
  font-size: 14px;
}

/* ！！关键：删除原硬编码的.active样式，完全由动态style控制 */
/* 若保留会覆盖动态样式，需注释或删除 */
/* .filter-btn.active {
  background-color: #00c48c;
  color: white;
  border-color: #00c48c;
} */

.search-results {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.reset-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 14px;
}

.no-results {
  text-align: center;
  padding: 40px 20px;
  color: #888;
}

.no-results i {
  font-size: 40px;
  margin-bottom: 15px;
  opacity: 0.5;
}

.contestants-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.contestant-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 6px;
  background-color: #f9f9f9;
  transition: transform 0.2s;
}

.contestant-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.contestant-rank {
  width: 30px;
  height: 30px;
  background-color: #00c48c;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 10px;
}

.contestant-img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 15px;
  border: 2px solid #eee;
}

.contestant-info {
  flex: 1;
}

.contestant-name {
  font-weight: bold;
  margin-bottom: 3px;
}

.contestant-id {
  font-size: 12px;
  color: #888;
  margin-bottom: 3px;
}

.contestant-votes {
  font-size: 12px;
  color: #00c48c;
}

/* 投票按钮：用动态样式，删除原固定颜色 */
.vote-button {
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  transition: opacity 0.3s;
}

.vote-button:hover {
  opacity: 0.9; /* 通用hover效果 */
}

.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  z-index: 1000;
  animation: fadeInOut 2s;
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
  }
  20% {
    opacity: 1;
  }
  80% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

.page-header {
  color: white;
  text-align: center;
}

.my-swipe {
  margin: 10px;
  border-radius: 8px;
  overflow: hidden;
  height: 200px;

  .carousel-slide {
    width: 100%;
    height: 100%;

    .slide-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .slide-content {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      color: #333;
    }
  }
}
/* 演员列表项样式 */
.players-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.grid-mode {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  .player-item {
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 18px 10px;
    position: relative;

    .player-rank {
      position: absolute;
      top: 10px;
      right: 10px;
    }

    .player-info {
      align-items: center;
      margin-top: 10px;
    }

    .van-button {
      margin-top: 10px;
      width: 90%;
    }
  }
}

/* 列表模式 */

.players-container.list-mode .player-item {
  flex-direction: row;
  padding: 15px;
  align-items: center;
}

.players-container.list-mode .player-avatar {
  width: 60px;
  height: 60px;
}

.players-container.list-mode .player-info {
  flex: 1;
  margin-left: 15px;
  align-items: flex-start;
}

.players-container.list-mode .player-desc {
  display: none;
}

// .players-container.list-mode .vote-btn {
//   margin-left: auto;
//   min-width: 80px;
// }

/* 卡片模式 */

.players-container.card-mode .player-item {
  flex-direction: column;
  align-items: flex-start;
  padding: 20px;
}

.players-container.card-mode .player-header {
  display: flex;
  width: 100%;
  align-items: center;
  margin-bottom: 15px;
}

.players-container.card-mode .player-info {
  align-items: flex-start;
  width: 100%;
}

.players-container.card-mode .player-desc {
  margin: 10px 0;
  line-height: 1.6;
}

.players-container.card-mode .van-button {
  width: 100%;
  margin-top: 15px;
}
/* 演员项通用样式 */
.player-item {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  transition: transform 0.3s, box-shadow 0.3s;
  position: relative;

  &:active {
    transform: translateY(-3px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
  }
}

.player-rank {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  background: #f5f5f5;
  color: #666;
  font-size: 13px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  z-index: 1;
  margin-right: 5px;
  &.first {
    background: linear-gradient(135deg, #ffd700 0%, #ffa500 100%);
    color: white;
    box-shadow: 0 2px 8px rgba(255, 165, 0, 0.3);
  }

  &.second {
    background: linear-gradient(135deg, #e0e0e0 0%, #a9a9a9 100%);
    color: white;
    box-shadow: 0 2px 8px rgba(169, 169, 169, 0.3);
  }

  &.third {
    background: linear-gradient(135deg, #cd7f32 0%, #d2691e 100%);
    color: white;
    box-shadow: 0 2px 8px rgba(210, 105, 30, 0.3);
  }
}
</style>
